#include "iap_server.h"
#include "ui_iap_server.h"
#include <QHostAddress>
#include <QFileDialog>
#include <QFileInfo>

IAP_Server::IAP_Server(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::IAP_Server)
{
    ui->setupUi(this);


    //分配空间
    tcpServer = new QTcpServer(this);

}

IAP_Server::~IAP_Server()
{
    delete ui;
}

void IAP_Server::on_buttonBind_clicked()
{
    quint16 port = ui->editPort->text().toInt();
    tcpServer->listen(QHostAddress::Any,port);



    ui->buttonBind->setEnabled(false);

    connect(tcpServer,&QTcpServer::newConnection,
    [=]()
    {
        //取出建立连接的套接字
        tcpSocket = tcpServer->nextPendingConnection();
        //获取对方的ip和端口
        QString ip = tcpSocket->peerAddress().toString();
        quint16 port = tcpSocket->peerPort();

        QString str = QString("[%1:%2]连接").arg(ip).arg(port);
        ui->editMain->append(str);
        ui->labelLinked->setText("已连接");

        //成功链接后按选择文件
        ui->buttonSelectFiles->setEnabled(true);
        ui->labelStatusBar->setText(str);
        ui->buttonDIsconnect->setEnabled(true);

        connect(tcpSocket,&QTcpSocket::disconnected,
        [=]()
        {
            ui->buttonDIsconnect->setEnabled(false);
            ui->labelLinked->setText("连接关闭");
            ui->buttonSelectFiles->setEnabled(false);
            ui->buttonStartSend->setEnabled(false);
            ui->buttonStopSend->setEnabled(false);
            ui->editMain->append("TCP连接关闭");
            tcpSocket->close();
        });
    });

    connect(&timer,&QTimer::timeout,
            [=]()
            {
                sendData();

            }
            );

}

void IAP_Server::on_buttonSelectFiles_clicked()
{
    //选择文件

    QString filePath = QFileDialog::getOpenFileName(this,"open","../");
    if(false == filePath.isEmpty())//如果选择的文件有效
    {
        fileName.clear();
        fileSize=0;
        //获取文件信息
        QFileInfo info(filePath);
        fileName = info.fileName();//获取文件名字
        fileSize = info.size();//获取文件大小
        QString fileinfo = QString("已选择文件%1,大小%2KB").arg(fileName).arg(fileSize/1024);
        ui->editMain->append(fileinfo);
        ui->progressBar->setMaximum(fileSize/1024);

        sendSize = 0;
        //只读方式打开文件
        //1.指定文件的名字
        file.setFileName(filePath);

        bool isOK = file.open(QIODevice::ReadOnly);
        if(isOK == false)
        {
            //打开文件失败
            ui->editMain->append("打开固件文件失败");
        }
        else
        {
            ui->buttonSelectFiles->setEnabled(false);
            ui->buttonStartSend->setEnabled(true);
            ui->editFilePath->setText(filePath);
            ui->labelStatusBar->setText("选择固件"+filePath);
        }

    }
    else
    {
        //选择文件路径无效
        ui->editMain->append("选择固件文件路径无效");
    }
}

void IAP_Server::on_buttonStartSend_clicked()
{
    ui->buttonStartSend->setEnabled(false);
    ui->buttonStopSend->setEnabled(true);
    //先发送文件的头部信息
    timer.start(1000/ui->horizontalSlider->value());
    //发送真正的信息
    ui->horizontalSlider->setEnabled(false);
}

void IAP_Server::sendData()
{
    qint64 len = 0;

        char buf[1024]={0};//每次发送数据的大小

        //读数据
        len = file.read(buf,sizeof(buf));
        //发数据 读多少 发多少
        len = tcpSocket->write(buf,len);

        //发送数据要累加
        sendSize+=len;

        ui->progressBar->setValue(sendSize/1024);
        QString str = QString("[%1]已发送 %2 字节数据(%3/%4).").arg(ui->progressBar->text()).arg(len).arg(sendSize).arg(fileSize);
        ui->editMain->append(str);
        ui->labelStatusBar->setText(str);

    if(len <=0)
    {
        QString str = QString("[传输结束]共发送 %1 字节数据.").arg(sendSize);
        ui->editMain->append(str);
        ui->labelStatusBar->setText(str);

        timer.stop();
        //是否发送数据完毕
        if(sendSize == fileSize)
        {
            //发送完毕
            ui->editMain->append("文件发送完毕！");
            file.close();

            //把客户端断开
            tcpSocket->disconnectFromHost();
            tcpSocket->close();
        }
        else
        {
            //发送完毕
            ui->editMain->append("文件没有发送完！请重试");
            file.close();

            //把客户端断开
            tcpSocket->disconnectFromHost();
            tcpSocket->close();
        }
        //ui->buttonSelectFiles->setEnabled(true);
        ui->buttonStartSend->setEnabled(false);
        ui->buttonStopSend->setEnabled(false);
        ui->horizontalSlider->setEnabled(true);
    }

}


void IAP_Server::on_buttonStopSend_clicked()
{
    timer.stop();
    ui->buttonStartSend->setEnabled(true);
    ui->buttonStopSend->setEnabled(false);
    ui->horizontalSlider->setEnabled(true);
}

void IAP_Server::on_horizontalSlider_sliderMoved(int position)
{
    ui->label_KB->setText(QString::number(ui->horizontalSlider->value())+"kB/s");
}

void IAP_Server::on_horizontalSlider_actionTriggered(int action)
{

}

void IAP_Server::on_buttonDIsconnect_clicked()
{
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
    if(ui->progressBar->value()!=0)
    {
        file.close();
        ui->buttonStartSend->setEnabled(false);
        ui->buttonStopSend->setEnabled(false);
        ui->horizontalSlider->setEnabled(true);
        ui->labelStatusBar->setText("主动断开和客户端的连接");
    }
}
